package com.app.mingluxing.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.app.mingluxing.R;
import com.app.mingluxing.adapter.MyBabyAdapter;
import com.app.mingluxing.base.BaseFragment;
import com.app.mingluxing.bean.MyResult;
import com.app.mingluxing.mqtt.MqttManager;
import com.app.mingluxing.mqttsource.MqttException;
import com.app.mingluxing.my.AboutActivity;
import com.app.mingluxing.my.AddBabyActivity;
import com.app.mingluxing.my.BabyDetailsActivity;
import com.app.mingluxing.my.SettingActivity;
import com.app.mingluxing.net.HttpUtil;
import com.app.mingluxing.ui.LoginActivity;
import com.app.mingluxing.utils.CommonUtils;
import com.app.mingluxing.utils.Constant;
import com.app.mingluxing.widget.CircleImageView;
import com.app.mingluxing.widget.ListViewForScrollView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

/**
 * 我的fragment
 * Created by Aaron on 2015/7/20.
 */
public class MyFragement extends BaseFragment implements View.OnClickListener {

    private CircleImageView cv_headpic;
    private List<MyResult.MyData> tempList;
    private MyBabyAdapter myBabyAdapter;
    private Intent mIntent;
    //    private int phoneNum;
    private TextView tv_name;
    private ListViewForScrollView lv_my_baby;
    //    public DisplayImageOptions options;
    private int[] bgPics = {R.drawable.my_bg_1, R.drawable.my_bg_2, R.drawable.my_bg_3, R.drawable.my_bg_4
            , R.drawable.my_bg_5, R.drawable.my_bg_6, R.drawable.my_bg_7, R.drawable.my_bg_8};
    private RelativeLayout rl_my_introduce;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View myView = View.inflate(getActivity(), R.layout.fragment_my, null);

//        options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(R.drawable.icon_person)
//                .showImageForEmptyUri(R.drawable.icon_person)
//                .showImageOnFail(R.drawable.icon_person)
//                .resetViewBeforeLoading(true)
//                .cacheOnDisk(true).cacheInMemory(true)
//                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
//                .bitmapConfig(Bitmap.Config.RGB_565)
//                .considerExifParams(true)
//                .displayer(new SimpleBitmapDisplayer()).build();

        tempList = new ArrayList<MyResult.MyData>();

        initWidget(myView);

//        Random r = new Random();

//        int showInt = r.nextInt(8);

//        LogUtil.e("tag", "随机数===" + showInt);

        rl_my_introduce.setBackgroundResource(bgPics[new Random().nextInt(8)]);

        return myView;
    }

    @Override
    public void onResume() {
        super.onResume();

        tv_name.setText(sp.getString(Constant.NICKNAME, ""));

        Glide.with(getActivity())
                .load(sp.getString(Constant.USERIMG, ""))
                .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .placeholder(R.drawable.icon_person)
                .into(cv_headpic);

        getData();
    }

//    private void setData() {
//        tv_name.setText(sp.getString(Constant.NICKNAME, ""));
//        ImageLoader.getInstance().displayImage(sp.getString(Constant.USERIMG, ""), cv_headpic, options);
//    }

    private void getData() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取中...", getActivity(), Constant.WEB_ROOT + Constant.MYLIST, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            MyResult myResult = JSONObject.parseObject(str, MyResult.class);
                            if (Constant.STATUS_SUCCESS == myResult.code) {
                                if (myResult.data != null) {
                                    tempList = myResult.data;
//                            if (tempList.size() > 0) {
                                    myBabyAdapter.setData(tempList);
                                    myBabyAdapter.notifyDataSetChanged();
//                            }

                                }
                            } else {

                                showToast(Constant.showErrorMsg(myResult.code, getActivity()));

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }
                    }
                }, null);
    }

    private void initWidget(View myView) {

        View headView = View.inflate(getActivity(), R.layout.head_my_fragment, null);

        lv_my_baby = (ListViewForScrollView) myView.findViewById(R.id.lv_my_baby);

        lv_my_baby.addHeaderView(headView);

        rl_my_introduce = (RelativeLayout) headView.findViewById(R.id.rl_my_introduce);
        cv_headpic = (CircleImageView) headView.findViewById(R.id.cv_headpic);
        tv_name = (TextView) headView.findViewById(R.id.tv_name);

        TextView tv_title = (TextView) myView.findViewById(R.id.tv_title);
        tv_title.setText(getResources().getString(R.string.my));

        TextView tv_exit = (TextView) myView.findViewById(R.id.tv_exit);

        TextView tv_clear_cache = (TextView) myView.findViewById(R.id.tv_clear_cache);

        lv_my_baby = (ListViewForScrollView) myView.findViewById(R.id.lv_my_baby);

        lv_my_baby.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                --position;
                mIntent = new Intent(getActivity(), BabyDetailsActivity.class);
                if (tempList != null) {
                    mIntent.putExtra("id", tempList.get(position).id);
                    mIntent.putExtra("classInfo", tempList.get(position).classInfo);
                    mIntent.putExtra("level", tempList.get(position).level);
                }
                startActivity(mIntent);
            }
        });

        RelativeLayout rl_add_baby = (RelativeLayout) myView.findViewById(R.id.rl_add_baby);
        RelativeLayout rl_about = (RelativeLayout) myView.findViewById(R.id.rl_about);
//        RelativeLayout rl_version = (RelativeLayout) myView.findViewById(R.id.rl_version);

        rl_my_introduce.setOnClickListener(this);
        rl_add_baby.setOnClickListener(this);
        rl_about.setOnClickListener(this);
//        rl_version.setOnClickListener(this);
        tv_exit.setOnClickListener(this);
        tv_clear_cache.setOnClickListener(this);

//        //版本号
//        tv_version_name.setText(getPackageInfo(getActivity()).versionName);

        myBabyAdapter = new MyBabyAdapter(getActivity(), tempList);
        lv_my_baby.setAdapter(myBabyAdapter);

    }

//    public PackageInfo getPackageInfo(Context context) {
//        PackageInfo pi = null;
//
//        try {
//            PackageManager pm = context.getPackageManager();
//            pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
//
//            return pi;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return pi;
//    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rl_my_introduce://进入我的信息修改页面

                mIntent = new Intent(getActivity(), SettingActivity.class);

                startActivity(mIntent);
                break;
            case R.id.rl_about://进入关于页面

                mIntent = new Intent(getActivity(), AboutActivity.class);
                startActivity(mIntent);

                break;

//            case R.id.rl_version://版本
////                showToast("已是最新版本");
//                UmengUpdateAgent.setUpdateOnlyWifi(false);
////                  UmengUpdateAgent.forceUpdate(getActivity());
//
//                UmengUpdateAgent.setUpdateAutoPopup(false);
//                UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
//
//                    @Override
//                    public void onUpdateReturned(int updateStatus, UpdateResponse updateInfo) {
//                        switch (updateStatus) {
//                            case UpdateStatus.Yes: // has update
//                                UmengUpdateAgent.showUpdateDialog(getActivity(), updateInfo);
//                                break;
//                            case UpdateStatus.No: // has no update
//                                Toast.makeText(getActivity(), "已是最新版本", Toast.LENGTH_SHORT).show();
//                                break;
//                            case UpdateStatus.NoneWifi: // none wifi
//                                Toast.makeText(getActivity(), "没有wifi连接,只在wifi下更新", Toast.LENGTH_SHORT).show();
//                                break;
//                            case UpdateStatus.Timeout: // time out
//                                Toast.makeText(getActivity(), "超时", Toast.LENGTH_SHORT).show();
//                                break;
//                        }
//                    }
//                });
//                UmengUpdateAgent.update(getActivity());
//
//                break;

            case R.id.rl_add_baby://进入添加宝宝页面

                mIntent = new Intent(getActivity(), AddBabyActivity.class);
                startActivity(mIntent);

                break;
            case R.id.tv_clear_cache://清除缓存

                //清除图片缓存
                ImageLoader.getInstance().clearDiskCache();
                ImageLoader.getInstance().clearMemoryCache();

                showToast("已清除");

                break;

            case R.id.tv_exit://退出

                quit();

                break;

        }
    }

    //退出
    private void quit() {

        new AlertDialog.Builder(getActivity()).setTitle("提示").setMessage("确定要退出吗?").setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                Set<String> remaindSet = sp.getStringSet(Constant.REMAIND + sp.getString(Constant.USERID, ""), new LinkedHashSet<String>());
                String userId = sp.getString(Constant.USERID, "");

                //删除用户的数据信息
                sp.edit().clear().apply();
                //保存 消息不提醒的topic至文件中
                CommonUtils.fileSave(Constant.REMAIND + userId, remaindSet);

                dialog.dismiss();

                try {

                    if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                        MqttManager.getInstance().getMqttClient().disconnect();

                } catch (MqttException e) {
                    e.printStackTrace();
                    showToast("退出失败");
                }

                //退出mqtt
                mApplication.exitMqtt();

                //回到登录页面
                mIntent = new Intent(getActivity(), LoginActivity.class);
                startActivity(mIntent);
            }
        }).show();

    }

}
